<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>4. More Control Flow Tools 深入流程控制 &mdash; Python v2.7 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.7',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v2.7 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v2.7 documentation" href="../index.html" />
    <link rel="up" title="The Python Tutorial" href="index.html" />
    <link rel="next" title="5. Data Structures 数据结构" href="datastructures.html" />
    <link rel="prev" title="3. An Informal Introduction to Python Python 概要介绍" href="introduction.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
 

  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             accesskey="M">modules</a> |</li>
        <li class="right" >
          <a href="datastructures.html" title="5. Data Structures 数据结构"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="3. An Informal Introduction to Python Python 概要介绍"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.7 documentation</a> &raquo;</li>

          <li><a href="index.html" accesskey="U">The Python Tutorial</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="more-control-flow-tools">
<span id="tut-morecontrol"></span><h1>4. More Control Flow Tools 深入流程控制<a class="headerlink" href="#more-control-flow-tools" title="Permalink to this headline">¶</a></h1>
<p>Besides the <a class="reference external" href="../reference/compound_stmts.html#while"><tt class="xref docutils literal"><span class="pre">while</span></tt></a> statement just introduced, Python knows the usual
control flow statements known from other languages, with some twists.</p>
<p>除了前面介绍的 <a class="reference external" href="../reference/compound_stmts.html#while"><tt class="xref docutils literal"><span class="pre">while</span></tt></a> 语句，Python 还从其它语言借鉴了一些流
程控制功能，并有所改变。</p>
<div class="section" id="if-statements-if">
<span id="tut-if"></span><h2>4.1. <a class="reference external" href="../reference/compound_stmts.html#if"><tt class="xref docutils literal"><span class="pre">if</span></tt></a> Statements <a class="reference external" href="../reference/compound_stmts.html#if"><tt class="xref docutils literal"><span class="pre">if</span></tt></a> 語句<a class="headerlink" href="#if-statements-if" title="Permalink to this headline">¶</a></h2>
<p>Perhaps the most well-known statement type is the <a class="reference external" href="../reference/compound_stmts.html#if"><tt class="xref docutils literal"><span class="pre">if</span></tt></a> statement.  For
example:</p>
<p>也许最有名的是 if 语句。例如</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="nb">raw_input</span><span class="p">(</span><span class="s">&quot;Please enter an integer: &quot;</span><span class="p">))</span>
<span class="go">Please enter an integer: 42</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span>
<span class="gp">... </span>     <span class="n">x</span> <span class="o">=</span> <span class="mi">0</span>
<span class="gp">... </span>     <span class="k">print</span> <span class="s">&#39;Negative changed to zero&#39;</span>
<span class="gp">... </span><span class="k">elif</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="gp">... </span>     <span class="k">print</span> <span class="s">&#39;Zero&#39;</span>
<span class="gp">... </span><span class="k">elif</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
<span class="gp">... </span>     <span class="k">print</span> <span class="s">&#39;Single&#39;</span>
<span class="gp">... </span><span class="k">else</span><span class="p">:</span>
<span class="gp">... </span>     <span class="k">print</span> <span class="s">&#39;More&#39;</span>
<span class="gp">...</span>
<span class="go">More</span>
</pre></div>
</div>
<p>There can be zero or more <a class="reference external" href="../reference/compound_stmts.html#elif"><tt class="xref docutils literal"><span class="pre">elif</span></tt></a> parts, and the <a class="reference external" href="../reference/compound_stmts.html#else"><tt class="xref docutils literal"><span class="pre">else</span></tt></a> part is
optional.  The keyword &#8216;<a class="reference external" href="../reference/compound_stmts.html#elif"><tt class="xref docutils literal"><span class="pre">elif</span></tt></a>&#8216; is short for &#8216;else if&#8217;, and is useful
to avoid excessive indentation.  An  <a class="reference external" href="../reference/compound_stmts.html#if"><tt class="xref docutils literal"><span class="pre">if</span></tt></a> ... <a class="reference external" href="../reference/compound_stmts.html#elif"><tt class="xref docutils literal"><span class="pre">elif</span></tt></a> ...
<a class="reference external" href="../reference/compound_stmts.html#elif"><tt class="xref docutils literal"><span class="pre">elif</span></tt></a> ... sequence is a substitute for the <tt class="docutils literal"><span class="pre">switch</span></tt> or
<tt class="docutils literal"><span class="pre">case</span></tt> statements found in other languages.</p>
<p>可能会有零到多个 elif 部分，else 是可选的。关键字“elif” 是“ else if
”的缩写，这个可以有效避免过深的缩进。if ... elif ... elif ... 序列用
于替代其它语言中的 switch 或 case 语句。</p>
</div>
<div class="section" id="for-statements-for">
<span id="tut-for"></span><h2>4.2. <a class="reference external" href="../reference/compound_stmts.html#for"><tt class="xref docutils literal"><span class="pre">for</span></tt></a> Statements <a class="reference external" href="../reference/compound_stmts.html#for"><tt class="xref docutils literal"><span class="pre">for</span></tt></a> 语句<a class="headerlink" href="#for-statements-for" title="Permalink to this headline">¶</a></h2>
<p id="index-1471">The <a class="reference external" href="../reference/compound_stmts.html#for"><tt class="xref docutils literal"><span class="pre">for</span></tt></a> statement in Python differs a bit from what you may be used
to in C or Pascal.  Rather than always iterating over an arithmetic progression
of numbers (like in Pascal), or giving the user the ability to define both the
iteration step and halting condition (as C), Python&#8217;s <a class="reference external" href="../reference/compound_stmts.html#for"><tt class="xref docutils literal"><span class="pre">for</span></tt></a> statement
iterates over the items of any sequence (a list or a string), in the order that
they appear in the sequence.  For example (no pun intended):</p>
<p>Python 中的 for 语句和 C 或 Pascal 中的略有不同。通常的循环可能会依据
一个等差数值步进过程（如Pascal），或由用户来定义迭代步骤和中止条件（如 C
），Python 的 for 语句依据任意序列（链表或字符串）中的子项，按它们在序
列中的顺序来进行迭代。例如（没有暗指）：</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="c"># Measure some strings:</span>
<span class="gp">... </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;cat&#39;</span><span class="p">,</span> <span class="s">&#39;window&#39;</span><span class="p">,</span> <span class="s">&#39;defenestrate&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">a</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="n">x</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">cat 3</span>
<span class="go">window 6</span>
<span class="go">defenestrate 12</span>
</pre></div>
</div>
<p>It is not safe to modify the sequence being iterated over in the loop (this can
only happen for mutable sequence types, such as lists).  If you need to modify
the list you are iterating over (for example, to duplicate selected items) you
must iterate over a copy.  The slice notation makes this particularly
convenient:</p>
<p>在迭代过程中修改迭代序列不安全（只有在使用链表这样的可变序列时才会有这
样的情况）。如果你想要修改你迭代的序列（例如，复制选择项），你可以迭代
它的复本。使用切割标识就可以很方便的做到这一点</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">a</span><span class="p">[:]:</span> <span class="c"># make a slice copy of the entire list</span>
<span class="gp">... </span>   <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">6</span><span class="p">:</span> <span class="n">a</span><span class="o">.</span><span class="n">insert</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[&#39;defenestrate&#39;, &#39;cat&#39;, &#39;window&#39;, &#39;defenestrate&#39;]</span>
</pre></div>
</div>
</div>
<div class="section" id="the-range-function-range">
<span id="tut-range"></span><h2>4.3. The <a title="range" class="reference external" href="../library/functions.html#range"><tt class="xref docutils literal"><span class="pre">range()</span></tt></a> Function <a title="range" class="reference external" href="../library/functions.html#range"><tt class="xref docutils literal"><span class="pre">range()</span></tt></a> 函数<a class="headerlink" href="#the-range-function-range" title="Permalink to this headline">¶</a></h2>
<p>If you do need to iterate over a sequence of numbers, the built-in function
<a title="range" class="reference external" href="../library/functions.html#range"><tt class="xref docutils literal"><span class="pre">range()</span></tt></a> comes in handy.  It generates lists containing arithmetic
progressions:</p>
<p>如果你需要一个数值序列，内置函数range()会很方便，它生成一个等差级
数链表</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="go">[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</span>
</pre></div>
</div>
<p>The given end point is never part of the generated list; <tt class="docutils literal"><span class="pre">range(10)</span></tt> generates
a list of 10 values, the legal indices for items of a sequence of length 10.  It
is possible to let the range start at another number, or to specify a different
increment (even negative; sometimes this is called the &#8216;step&#8217;):</p>
<p>range(10) 生成了一个包含10个值的链表，它用链表的索引值填充了这个长度为
10的列表，所生成的链表中不包括范围中的结束值。也可以让range操作从另一
个数值开始，或者可以指定一个不同的步进值（甚至是负数，有时这也被称为
“步长”）</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
<span class="go">[5, 6, 7, 8, 9]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="go">[0, 3, 6, 9]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="o">-</span><span class="mi">10</span><span class="p">,</span> <span class="o">-</span><span class="mi">100</span><span class="p">,</span> <span class="o">-</span><span class="mi">30</span><span class="p">)</span>
<span class="go">[-10, -40, -70]</span>
</pre></div>
</div>
<p>To iterate over the indices of a sequence, you can combine <a title="range" class="reference external" href="../library/functions.html#range"><tt class="xref docutils literal"><span class="pre">range()</span></tt></a> and
<a title="len" class="reference external" href="../library/functions.html#len"><tt class="xref docutils literal"><span class="pre">len()</span></tt></a> as follows:</p>
<p>需要迭代链表索引的话，如下所示结合使 用range() 和 len()</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;Mary&#39;</span><span class="p">,</span> <span class="s">&#39;had&#39;</span><span class="p">,</span> <span class="s">&#39;a&#39;</span><span class="p">,</span> <span class="s">&#39;little&#39;</span><span class="p">,</span> <span class="s">&#39;lamb&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">a</span><span class="p">)):</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="n">i</span><span class="p">,</span> <span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
<span class="gp">...</span>
<span class="go">0 Mary</span>
<span class="go">1 had</span>
<span class="go">2 a</span>
<span class="go">3 little</span>
<span class="go">4 lamb</span>
</pre></div>
</div>
<p>In most such cases, however, it is convenient to use the <a title="enumerate" class="reference external" href="../library/functions.html#enumerate"><tt class="xref docutils literal"><span class="pre">enumerate()</span></tt></a>
function, see <a class="reference external" href="datastructures.html#tut-loopidioms"><em>Looping Techniques 循环技巧</em></a>.</p>
<p>不过，这种场合可以方便的使用 <a title="enumerate" class="reference external" href="../library/functions.html#enumerate"><tt class="xref docutils literal"><span class="pre">enumerate()</span></tt></a> ，请参见
<a class="reference external" href="datastructures.html#tut-loopidioms"><em>Looping Techniques 循环技巧</em></a> 。</p>
</div>
<div class="section" id="break-and-continue-statements-and-else-clauses-on-loops-break-continue-else">
<span id="tut-break"></span><h2>4.4. <a class="reference external" href="../reference/simple_stmts.html#break"><tt class="xref docutils literal"><span class="pre">break</span></tt></a> and <a class="reference external" href="../reference/simple_stmts.html#continue"><tt class="xref docutils literal"><span class="pre">continue</span></tt></a> Statements, and <a class="reference external" href="../reference/compound_stmts.html#else"><tt class="xref docutils literal"><span class="pre">else</span></tt></a> Clauses on Loops break 和 continue 语句, 以及 循环中的 else 子句<a class="headerlink" href="#break-and-continue-statements-and-else-clauses-on-loops-break-continue-else" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference external" href="../reference/simple_stmts.html#break"><tt class="xref docutils literal"><span class="pre">break</span></tt></a> statement, like in C, breaks out of the smallest enclosing
<a class="reference external" href="../reference/compound_stmts.html#for"><tt class="xref docutils literal"><span class="pre">for</span></tt></a> or <a class="reference external" href="../reference/compound_stmts.html#while"><tt class="xref docutils literal"><span class="pre">while</span></tt></a> loop.</p>
<p>break 语句和 C 中的类似，用于跳出最近的一级 for 或 while 循环。</p>
<p>The <a class="reference external" href="../reference/simple_stmts.html#continue"><tt class="xref docutils literal"><span class="pre">continue</span></tt></a> statement, also borrowed from C, continues with the next
iteration of the loop.</p>
<p><a class="reference external" href="../reference/simple_stmts.html#continue"><tt class="xref docutils literal"><span class="pre">continue</span></tt></a> 语句是从 C 中借鉴来的，它表示循环继续执行下一次迭代。</p>
<p>Loop statements may have an <tt class="docutils literal"><span class="pre">else</span></tt> clause; it is executed when the loop
terminates through exhaustion of the list (with <a class="reference external" href="../reference/compound_stmts.html#for"><tt class="xref docutils literal"><span class="pre">for</span></tt></a>) or when the
condition becomes false (with <a class="reference external" href="../reference/compound_stmts.html#while"><tt class="xref docutils literal"><span class="pre">while</span></tt></a>), but not when the loop is
terminated by a <a class="reference external" href="../reference/simple_stmts.html#break"><tt class="xref docutils literal"><span class="pre">break</span></tt></a> statement.  This is exemplified by the
following loop, which searches for prime numbers:</p>
<p>循环可以有一个 <tt class="docutils literal"><span class="pre">else</span></tt> 子句;它在循环迭代完整个列表（对于 <a class="reference external" href="../reference/compound_stmts.html#for"><tt class="xref docutils literal"><span class="pre">for</span></tt></a> ）或执行条件
为 false （对于 <a class="reference external" href="../reference/compound_stmts.html#while"><tt class="xref docutils literal"><span class="pre">while</span></tt></a> ）时执行，但循环被 <a class="reference external" href="../reference/simple_stmts.html#break"><tt class="xref docutils literal"><span class="pre">break</span></tt></a> 中止的情况下不会执行。
以下搜索素数的示例程序演示了这个子句</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">10</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">if</span> <span class="n">n</span> <span class="o">%</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="gp">... </span>            <span class="k">print</span> <span class="n">n</span><span class="p">,</span> <span class="s">&#39;equals&#39;</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="s">&#39;*&#39;</span><span class="p">,</span> <span class="n">n</span><span class="o">/</span><span class="n">x</span>
<span class="gp">... </span>            <span class="k">break</span>
<span class="gp">... </span>    <span class="k">else</span><span class="p">:</span>
<span class="gp">... </span>        <span class="c"># loop fell through without finding a factor</span>
<span class="gp">... </span>        <span class="k">print</span> <span class="n">n</span><span class="p">,</span> <span class="s">&#39;is a prime number&#39;</span>
<span class="gp">...</span>
<span class="go">2 is a prime number</span>
<span class="go">3 is a prime number</span>
<span class="go">4 equals 2 * 2</span>
<span class="go">5 is a prime number</span>
<span class="go">6 equals 2 * 3</span>
<span class="go">7 is a prime number</span>
<span class="go">8 equals 2 * 4</span>
<span class="go">9 equals 3 * 3</span>
</pre></div>
</div>
</div>
<div class="section" id="pass-statements-pass">
<span id="tut-pass"></span><h2>4.5. <a class="reference external" href="../reference/simple_stmts.html#pass"><tt class="xref docutils literal"><span class="pre">pass</span></tt></a> Statements <a class="reference external" href="../reference/simple_stmts.html#pass"><tt class="xref docutils literal"><span class="pre">pass</span></tt></a> 语句<a class="headerlink" href="#pass-statements-pass" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference external" href="../reference/simple_stmts.html#pass"><tt class="xref docutils literal"><span class="pre">pass</span></tt></a> statement does nothing. It can be used when a statement is
required syntactically but the program requires no action. For example:</p>
<p>pass 语句什么也不做。它用于那些语法上必须要有什么语句，但程序什么也不
做的场合，例如</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">pass</span>  <span class="c"># Busy-wait for keyboard interrupt (Ctrl+C)</span>
<span class="gp">...</span>
</pre></div>
</div>
<p>This is commonly used for creating minimal classes:</p>
<p>这通常用于创建最小结构的类</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">MyEmptyClass</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
</pre></div>
</div>
<p>Another place <a class="reference external" href="../reference/simple_stmts.html#pass"><tt class="xref docutils literal"><span class="pre">pass</span></tt></a> can be used is as a place-holder for a function or
conditional body when you are working on new code, allowing you to keep thinking
at a more abstract level.  The <a class="reference external" href="../reference/simple_stmts.html#pass"><tt class="xref docutils literal"><span class="pre">pass</span></tt></a> is silently ignored:</p>
<p>另一方面， <a class="reference external" href="../reference/simple_stmts.html#pass"><tt class="xref docutils literal"><span class="pre">pass</span></tt></a> 可以在创建新代码时用来做函数或控制体的占位
符。可以让你在更抽象的级别上思考。 <a class="reference external" href="../reference/simple_stmts.html#pass"><tt class="xref docutils literal"><span class="pre">pass</span></tt></a> 可以默默的被忽视</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">initlog</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">pass</span>   <span class="c"># Remember to implement this!</span>
<span class="gp">...</span>
</pre></div>
</div>
</div>
<div class="section" id="defining-functions">
<span id="tut-functions"></span><h2>4.6. Defining Functions 定义函数<a class="headerlink" href="#defining-functions" title="Permalink to this headline">¶</a></h2>
<p>We can create a function that writes the Fibonacci series to an arbitrary
boundary:</p>
<p>我们可以定义一个函数以生成任意上界的菲波那契数列</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">fib</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>    <span class="c"># write Fibonacci series up to n</span>
<span class="gp">... </span>    <span class="sd">&quot;&quot;&quot;Print a Fibonacci series up to n.&quot;&quot;&quot;</span>
<span class="gp">... </span>    <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
<span class="gp">... </span>    <span class="k">while</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">print</span> <span class="n">a</span><span class="p">,</span>
<span class="gp">... </span>        <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="o">+</span><span class="n">b</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c"># Now call the function we just defined:</span>
<span class="gp">... </span><span class="n">fib</span><span class="p">(</span><span class="mi">2000</span><span class="p">)</span>
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597</span>
</pre></div>
</div>
<p id="index-1472">The keyword <a class="reference external" href="../reference/compound_stmts.html#def"><tt class="xref docutils literal"><span class="pre">def</span></tt></a> introduces a function <em>definition</em>.  It must be
followed by the function name and the parenthesized list of formal parameters.
The statements that form the body of the function start at the next line, and
must be indented.</p>
<p>关键字 <a class="reference external" href="../reference/compound_stmts.html#def"><tt class="xref docutils literal"><span class="pre">def</span></tt></a> 引入了一个函数 <em>定义</em> 。在其后必须跟有函数名和包
括形式参数的圆括号。函数体语句从下一行开始，必须是缩进的。</p>
<p>The first statement of the function body can optionally be a string literal;
this string literal is the function&#8217;s documentation string, or <em>docstring</em>.
(More about docstrings can be found in the section <a class="reference internal" href="#tut-docstrings"><em>Documentation Strings 文档字符串</em></a>.)
There are tools which use docstrings to automatically produce online or printed
documentation, or to let the user interactively browse through code; it&#8217;s good
practice to include docstrings in code that you write, so make a habit of it.</p>
<p>函数体的第一行可以是一个字符串值，这个字符串是该函数的文档字符串
，或称 <em>docstring</em> 。（更进一步的文
档字符串介绍可以在这一节找到 <a class="reference internal" href="#tut-docstrings"><em>Documentation Strings 文档字符串</em></a> 。）有些工具使用文
档字符串在线的生成及打印文档，或者允许用户在代码中交互式的浏览；编写代
码进加入文档字符串是个好的风格，应该养成习惯。</p>
<p>The <em>execution</em> of a function introduces a new symbol table used for the local
variables of the function.  More precisely, all variable assignments in a
function store the value in the local symbol table; whereas variable references
first look in the local symbol table, then in the local symbol tables of
enclosing functions, then in the global symbol table, and finally in the table
of built-in names. Thus, global variables cannot be directly assigned a value
within a function (unless named in a <a class="reference external" href="../reference/simple_stmts.html#global"><tt class="xref docutils literal"><span class="pre">global</span></tt></a> statement), although they
may be referenced.</p>
<dl class="docutils">
<dt><em>执行</em> 函数时会为局部变量引入一个新的符号表。所有的局部变量都存储在这</dt>
<dd>个局部符号表中。引用参数时，会先从局部符号表中查找，然后是全局符号表，然
后是内置命名表。因此，全局参数虽然可以被引用，但它们不能在函数中直接
赋值（除非它们用 <a class="reference external" href="../reference/simple_stmts.html#global"><tt class="xref docutils literal"><span class="pre">global</span></tt></a> 语句命名）。</dd>
</dl>
<p>The actual parameters (arguments) to a function call are introduced in the local
symbol table of the called function when it is called; thus, arguments are
passed using <em>call by value</em> (where the <em>value</em> is always an object <em>reference</em>,
not the value of the object). <a class="footnote-reference" href="#id3" id="id1">[1]</a> When a function calls another function, a new
local symbol table is created for that call.</p>
<p>函数引用的实际参数在函数调用时引入局部符号表，因此，实参总是 <em>传值调用</em>
（这里的 <em>值</em> 总是一个对象 <em>引用</em> ，而不是该对象的值）。 <a class="footnote-reference" href="#id4" id="id2">[2]</a> 一个函数被另一个函
数调用时，一个新的局部符号表在调用过程中被创建。</p>
<p>A function definition introduces the function name in the current symbol table.
The value of the function name has a type that is recognized by the interpreter
as a user-defined function.  This value can be assigned to another name which
can then also be used as a function.  This serves as a general renaming
mechanism:</p>
<p>函数定义在当前符号表中引入函数名。作为用户定义函数，函数名有一个为解释
器认可的类型值。这个值可以赋给其它命名，使其能够作为一个函数来使用。这
就像一个重命名机制</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span>
<span class="go">&lt;function fib at 10042ed0&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">fib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89</span>
</pre></div>
</div>
<p>Coming from other languages, you might object that <tt class="docutils literal"><span class="pre">fib</span></tt> is not a function but
a procedure since it doesn&#8217;t return a value.  In fact, even functions without a
<a class="reference external" href="../reference/simple_stmts.html#return"><tt class="xref docutils literal"><span class="pre">return</span></tt></a> statement do return a value, albeit a rather boring one.  This
value is called <tt class="xref docutils literal"><span class="pre">None</span></tt> (it&#8217;s a built-in name).  Writing the value <tt class="xref docutils literal"><span class="pre">None</span></tt> is
normally suppressed by the interpreter if it would be the only value written.
You can see it if you really want to using <a class="reference external" href="../reference/simple_stmts.html#print"><tt class="xref docutils literal"><span class="pre">print</span></tt></a>:</p>
<p>你可能认为 <tt class="docutils literal"><span class="pre">fib</span></tt> 没有返回值，它不是一个函数（ function ），而是一个
过程（ procedure ）。实际上，即使函数没有 <a class="reference external" href="../reference/simple_stmts.html#return"><tt class="xref docutils literal"><span class="pre">return</span></tt></a> 语句，它也
有返回值，虽然是一个不讨人喜欢的。这个值被称为 <tt class="xref docutils literal"><span class="pre">None</span></tt> （这是一个内置命
名）。如果一个值只是 None 的话，通常解释器不会写出来，如果你真想要查看
它的话，可以这样做</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">fib</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">None</span>
</pre></div>
</div>
<p>It is simple to write a function that returns a list of the numbers of the
Fibonacci series, instead of printing it:</p>
<p>以下示例演示了如何从函数中返回一个包含菲波那契数列的数值链表，而不是打
印它</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">fib2</span><span class="p">(</span><span class="n">n</span><span class="p">):</span> <span class="c"># return Fibonacci series up to n</span>
<span class="gp">... </span>    <span class="sd">&quot;&quot;&quot;Return a list containing the Fibonacci series up to n.&quot;&quot;&quot;</span>
<span class="gp">... </span>    <span class="n">result</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">... </span>    <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
<span class="gp">... </span>    <span class="k">while</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">:</span>
<span class="gp">... </span>        <span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>    <span class="c"># see below</span>
<span class="gp">... </span>        <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="o">+</span><span class="n">b</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">result</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f100</span> <span class="o">=</span> <span class="n">fib2</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>    <span class="c"># call it</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f100</span>                <span class="c"># write the result</span>
<span class="go">[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]</span>
</pre></div>
</div>
<p>This example, as usual, demonstrates some new Python features:</p>
<p>和以前一样，这个例子演示了一些新的 Python 功能：</p>
<ul>
<li><p class="first">The <a class="reference external" href="../reference/simple_stmts.html#return"><tt class="xref docutils literal"><span class="pre">return</span></tt></a> statement returns with a value from a function.
<a class="reference external" href="../reference/simple_stmts.html#return"><tt class="xref docutils literal"><span class="pre">return</span></tt></a> without an expression argument returns <tt class="xref docutils literal"><span class="pre">None</span></tt>. Falling off
the end of a function also returns <tt class="xref docutils literal"><span class="pre">None</span></tt>.</p>
<p><a class="reference external" href="../reference/simple_stmts.html#return"><tt class="xref docutils literal"><span class="pre">return</span></tt></a> 语句从函数中返回一个值，不带表达式的
<a class="reference external" href="../reference/simple_stmts.html#return"><tt class="xref docutils literal"><span class="pre">return</span></tt></a> 返回 <tt class="xref docutils literal"><span class="pre">None</span></tt> 。过程结束后也会返回 <tt class="xref docutils literal"><span class="pre">None</span></tt>  。</p>
</li>
<li><p class="first">The statement <tt class="docutils literal"><span class="pre">result.append(a)</span></tt> calls a <em>method</em> of the list object
<tt class="docutils literal"><span class="pre">result</span></tt>.  A method is a function that &#8216;belongs&#8217; to an object and is named
<tt class="docutils literal"><span class="pre">obj.methodname</span></tt>, where <tt class="docutils literal"><span class="pre">obj</span></tt> is some object (this may be an expression),
and <tt class="docutils literal"><span class="pre">methodname</span></tt> is the name of a method that is defined by the object&#8217;s type.
Different types define different methods.  Methods of different types may have
the same name without causing ambiguity.  (It is possible to define your own
object types and methods, using <em>classes</em>, see <a class="reference external" href="classes.html#tut-classes"><em>Classes 类</em></a>)
The method <tt class="xref docutils literal"><span class="pre">append()</span></tt> shown in the example is defined for list objects; it
adds a new element at the end of the list.  In this example it is equivalent to
<tt class="docutils literal"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">result</span> <span class="pre">+</span> <span class="pre">[a]</span></tt>, but more efficient.</p>
<p>语句 <tt class="docutils literal"><span class="pre">result.append(b)</span></tt> 称为链表对象 <tt class="docutils literal"><span class="pre">result</span></tt> 的一个 <em>方法</em> （ method ）。方
法是一个“属于”某个对象的函数，它被命名为 <tt class="docutils literal"><span class="pre">obj.methodename</span></tt> ，这里的
<tt class="docutils literal"><span class="pre">obj</span></tt> 是某个对象（可能是一个表达式）， <tt class="docutils literal"><span class="pre">methodename</span></tt> 是某个在该对象类型定
义中的方法的命名。不同的类型定义不同的方法。不同类型可能有同样名字的
方法，但不会混淆。（当你定义自己的对象类型和方法时，可能会出现这种情
况， <em>class</em> 的定义方法详见 <a class="reference external" href="classes.html#tut-classes"><em>Classes 类</em></a> ）。示例中演示的
<tt class="xref docutils literal"><span class="pre">append()</span></tt> 方法
由链表对象定义，它向链表中加入一个新元素。在示例中它等同于</p>
</li>
</ul>
<p><tt class="docutils literal"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">result</span> <span class="pre">+</span> <span class="pre">[b]</span></tt> ，不过效率更高。</p>
</div>
<div class="section" id="more-on-defining-functions">
<span id="tut-defining"></span><h2>4.7. More on Defining Functions 深入函数定义<a class="headerlink" href="#more-on-defining-functions" title="Permalink to this headline">¶</a></h2>
<p>It is also possible to define functions with a variable number of arguments.
There are three forms, which can be combined.</p>
<p>有时需要定义参数个数可变的函数。有三种形式，我们可以组合使用它们。</p>
<div class="section" id="default-argument-values">
<span id="tut-defaultargs"></span><h3>4.7.1. Default Argument Values 参数默认值<a class="headerlink" href="#default-argument-values" title="Permalink to this headline">¶</a></h3>
<p>The most useful form is to specify a default value for one or more arguments.
This creates a function that can be called with fewer arguments than it is
defined to allow.  For example:</p>
<p>最有用的形式是给一个或多个参数指定默认值。这样创建的函数可以用较少的参
数来调用。例如</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">ask_ok</span><span class="p">(</span><span class="n">prompt</span><span class="p">,</span> <span class="n">retries</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">complaint</span><span class="o">=</span><span class="s">&#39;Yes or no, please!&#39;</span><span class="p">):</span>
    <span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
        <span class="n">ok</span> <span class="o">=</span> <span class="nb">raw_input</span><span class="p">(</span><span class="n">prompt</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">ok</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&#39;y&#39;</span><span class="p">,</span> <span class="s">&#39;ye&#39;</span><span class="p">,</span> <span class="s">&#39;yes&#39;</span><span class="p">):</span>
            <span class="k">return</span> <span class="bp">True</span>
        <span class="k">if</span> <span class="n">ok</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&#39;n&#39;</span><span class="p">,</span> <span class="s">&#39;no&#39;</span><span class="p">,</span> <span class="s">&#39;nop&#39;</span><span class="p">,</span> <span class="s">&#39;nope&#39;</span><span class="p">):</span>
            <span class="k">return</span> <span class="bp">False</span>
        <span class="n">retries</span> <span class="o">=</span> <span class="n">retries</span> <span class="o">-</span> <span class="mi">1</span>
        <span class="k">if</span> <span class="n">retries</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">IOError</span><span class="p">(</span><span class="s">&#39;refusenik user&#39;</span><span class="p">)</span>
        <span class="k">print</span> <span class="n">complaint</span>
</pre></div>
</div>
<p>This function can be called in several ways:</p>
<p>这个函数可以通过几种不同的方式调用：</p>
<ul class="simple">
<li>giving only the mandatory argument:
只给出必要的参数：
<tt class="docutils literal"><span class="pre">ask_ok('Do</span> <span class="pre">you</span> <span class="pre">really</span> <span class="pre">want</span> <span class="pre">to</span> <span class="pre">quit?')</span></tt></li>
<li>giving one of the optional arguments:
给出一个可选的参数：
<tt class="docutils literal"><span class="pre">ask_ok('OK</span> <span class="pre">to</span> <span class="pre">overwrite</span> <span class="pre">the</span> <span class="pre">file?',</span> <span class="pre">2)</span></tt></li>
<li>or even giving all arguments:
或者给出所有的参数：
<tt class="docutils literal"><span class="pre">ask_ok('OK</span> <span class="pre">to</span> <span class="pre">overwrite</span> <span class="pre">the</span> <span class="pre">file?',</span> <span class="pre">2,</span> <span class="pre">'Come</span> <span class="pre">on,</span> <span class="pre">only</span> <span class="pre">yes</span> <span class="pre">or</span> <span class="pre">no!')</span></tt></li>
</ul>
<p>This example also introduces the <a class="reference external" href="../reference/expressions.html#in"><tt class="xref docutils literal"><span class="pre">in</span></tt></a> keyword. This tests whether or
not a sequence contains a certain value.</p>
<p>这个例子还介绍了 <a class="reference external" href="../reference/expressions.html#in"><tt class="xref docutils literal"><span class="pre">in</span></tt></a> 关键字。它测定序列中是否包含某个确定的
值。</p>
<p>The default values are evaluated at the point of function definition in the
<em>defining</em> scope, so that :</p>
<p>默认值在函数 <em>定义</em> 作用域被解析，如下所示</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">i</span> <span class="o">=</span> <span class="mi">5</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">arg</span><span class="o">=</span><span class="n">i</span><span class="p">):</span>
    <span class="k">print</span> <span class="n">arg</span>

<span class="n">i</span> <span class="o">=</span> <span class="mi">6</span>
<span class="n">f</span><span class="p">()</span>
</pre></div>
</div>
<p>will print <tt class="docutils literal"><span class="pre">5</span></tt>.</p>
<p><strong>Important warning:</strong>  The default value is evaluated only once. This makes a
difference when the default is a mutable object such as a list, dictionary, or
instances of most classes.  For example, the following function accumulates the
arguments passed to it on subsequent calls :</p>
<p><strong>重要警告</strong> 默认值只解析一次。这造成字典、列表或大部分类实例等可变对象的行为会与期待的不太一样。例如，下例的函数在每次调用时都造成参数的累加</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">L</span><span class="o">=</span><span class="p">[]):</span>
    <span class="n">L</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">L</span>

<span class="k">print</span> <span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="k">print</span> <span class="n">f</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="k">print</span> <span class="n">f</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
</pre></div>
</div>
<p>This will print :</p>
<p>这样会打印出</p>
<div class="highlight-python"><div class="highlight"><pre><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">]</span>
<span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
</pre></div>
</div>
<p>If you don&#8217;t want the default to be shared between subsequent calls, you can
write the function like this instead:</p>
<p>如果你不想在随后的调用中共享默认值，可以像这样写函数</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">L</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">L</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
        <span class="n">L</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">L</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">L</span>
</pre></div>
</div>
</div>
<div class="section" id="keyword-arguments">
<span id="tut-keywordargs"></span><h3>4.7.2. Keyword Arguments 关键字参数<a class="headerlink" href="#keyword-arguments" title="Permalink to this headline">¶</a></h3>
<p>Functions can also be called using keyword arguments of the form <tt class="docutils literal"><span class="pre">keyword</span> <span class="pre">=</span>
<span class="pre">value</span></tt>.  For instance, the following function:</p>
<p>函数可以通过关键字参数的形式来调用，形如 <tt class="docutils literal"><span class="pre">keyword</span> <span class="pre">=</span> <span class="pre">value</span></tt> 。例如，
以下的函数</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">parrot</span><span class="p">(</span><span class="n">voltage</span><span class="p">,</span> <span class="n">state</span><span class="o">=</span><span class="s">&#39;a stiff&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&#39;voom&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s">&#39;Norwegian Blue&#39;</span><span class="p">):</span>
    <span class="k">print</span> <span class="s">&quot;-- This parrot wouldn&#39;t&quot;</span><span class="p">,</span> <span class="n">action</span><span class="p">,</span>
    <span class="k">print</span> <span class="s">&quot;if you put&quot;</span><span class="p">,</span> <span class="n">voltage</span><span class="p">,</span> <span class="s">&quot;volts through it.&quot;</span>
    <span class="k">print</span> <span class="s">&quot;-- Lovely plumage, the&quot;</span><span class="p">,</span> <span class="nb">type</span>
    <span class="k">print</span> <span class="s">&quot;-- It&#39;s&quot;</span><span class="p">,</span> <span class="n">state</span><span class="p">,</span> <span class="s">&quot;!&quot;</span>
</pre></div>
</div>
<p>could be called in any of the following ways:</p>
<p>可以用以下的任一方法调用</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parrot</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span>
<span class="n">parrot</span><span class="p">(</span><span class="n">action</span> <span class="o">=</span> <span class="s">&#39;VOOOOOM&#39;</span><span class="p">,</span> <span class="n">voltage</span> <span class="o">=</span> <span class="mi">1000000</span><span class="p">)</span>
<span class="n">parrot</span><span class="p">(</span><span class="s">&#39;a thousand&#39;</span><span class="p">,</span> <span class="n">state</span> <span class="o">=</span> <span class="s">&#39;pushing up the daisies&#39;</span><span class="p">)</span>
<span class="n">parrot</span><span class="p">(</span><span class="s">&#39;a million&#39;</span><span class="p">,</span> <span class="s">&#39;bereft of life&#39;</span><span class="p">,</span> <span class="s">&#39;jump&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>but the following calls would all be invalid:</p>
<p>不过以下几种调用是无效的</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parrot</span><span class="p">()</span>                     <span class="c"># required argument missing</span>
<span class="n">parrot</span><span class="p">(</span><span class="n">voltage</span><span class="o">=</span><span class="mf">5.0</span><span class="p">,</span> <span class="s">&#39;dead&#39;</span><span class="p">)</span>  <span class="c"># non-keyword argument following keyword</span>
<span class="n">parrot</span><span class="p">(</span><span class="mi">110</span><span class="p">,</span> <span class="n">voltage</span><span class="o">=</span><span class="mi">220</span><span class="p">)</span>     <span class="c"># duplicate value for argument</span>
<span class="n">parrot</span><span class="p">(</span><span class="n">actor</span><span class="o">=</span><span class="s">&#39;John Cleese&#39;</span><span class="p">)</span>  <span class="c"># unknown keyword</span>
</pre></div>
</div>
<p>In general, an argument list must have any positional arguments followed by any
keyword arguments, where the keywords must be chosen from the formal parameter
names.  It&#8217;s not important whether a formal parameter has a default value or
not.  No argument may receive a value more than once &#8212; formal parameter names
corresponding to positional arguments cannot be used as keywords in the same
calls. Here&#8217;s an example that fails due to this restriction:</p>
<p>通常，参数列表中的每一个关键字都必须来自于形式参数，每个参数都有对应的
关键字。形式参数有没有默认值并不重要。实际参数不能一次赋多个值——形式参
数不能在同一次调用中同时使用位置和关键字绑定值。这里有一个例子演示了在
这种约束下所出现的失败情况</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">function</span><span class="p">(</span><span class="n">a</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">function</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">a</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">TypeError</span>: <span class="n-Identifier">function() got multiple values for keyword argument &#39;a&#39;</span>
</pre></div>
</div>
<p>When a final formal parameter of the form <tt class="docutils literal"><span class="pre">**name</span></tt> is present, it receives a
dictionary (see <a class="reference external" href="../library/stdtypes.html#typesmapping"><em>Mapping Types &#8212; dict</em></a>) containing all keyword arguments except for
those corresponding to a formal parameter.  This may be combined with a formal
parameter of the form <tt class="docutils literal"><span class="pre">*name</span></tt> (described in the next subsection) which
receives a tuple containing the positional arguments beyond the formal parameter
list.  (<tt class="docutils literal"><span class="pre">*name</span></tt> must occur before <tt class="docutils literal"><span class="pre">**name</span></tt>.) For example, if we define a
function like this:</p>
<p>引入一个形如 <tt class="docutils literal"><span class="pre">**name</span></tt> 的参数时，它接收一个字典（参见
<a class="reference external" href="../library/stdtypes.html#typesmapping"><em>Mapping Types &#8212; dict</em></a> ） ，该字典包含了所有未出现
在形式参数列表中的关键字参数。这里可能还会组合使用一个形如 <tt class="docutils literal"><span class="pre">*name</span></tt>
（下一小节詳細介绍） 的形
式参数，它接收一个元组（下一节中会详细介绍），包含了所有没有出现在形式
参数列表中的参数值。（ <tt class="docutils literal"><span class="pre">*name</span></tt> 必须在 <tt class="docutils literal"><span class="pre">**name</span></tt> 之前出现） 例如，我们这样定
义一个函数</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">cheeseshop</span><span class="p">(</span><span class="n">kind</span><span class="p">,</span> <span class="o">*</span><span class="n">arguments</span><span class="p">,</span> <span class="o">**</span><span class="n">keywords</span><span class="p">):</span>
    <span class="k">print</span> <span class="s">&quot;-- Do you have any&quot;</span><span class="p">,</span> <span class="n">kind</span><span class="p">,</span> <span class="s">&quot;?&quot;</span>
    <span class="k">print</span> <span class="s">&quot;-- I&#39;m sorry, we&#39;re all out of&quot;</span><span class="p">,</span> <span class="n">kind</span>
    <span class="k">for</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">arguments</span><span class="p">:</span> <span class="k">print</span> <span class="n">arg</span>
    <span class="k">print</span> <span class="s">&quot;-&quot;</span> <span class="o">*</span> <span class="mi">40</span>
    <span class="n">keys</span> <span class="o">=</span> <span class="n">keywords</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span>
    <span class="n">keys</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
    <span class="k">for</span> <span class="n">kw</span> <span class="ow">in</span> <span class="n">keys</span><span class="p">:</span> <span class="k">print</span> <span class="n">kw</span><span class="p">,</span> <span class="s">&quot;:&quot;</span><span class="p">,</span> <span class="n">keywords</span><span class="p">[</span><span class="n">kw</span><span class="p">]</span>
</pre></div>
</div>
<p>It could be called like this:</p>
<p>它可以像这样调用</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">cheeseshop</span><span class="p">(</span><span class="s">&quot;Limburger&quot;</span><span class="p">,</span> <span class="s">&quot;It&#39;s very runny, sir.&quot;</span><span class="p">,</span>
           <span class="s">&quot;It&#39;s really very, VERY runny, sir.&quot;</span><span class="p">,</span>
           <span class="n">shopkeeper</span><span class="o">=</span><span class="s">&#39;Michael Palin&#39;</span><span class="p">,</span>
           <span class="n">client</span><span class="o">=</span><span class="s">&quot;John Cleese&quot;</span><span class="p">,</span>
           <span class="n">sketch</span><span class="o">=</span><span class="s">&quot;Cheese Shop Sketch&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>and of course it would print:</p>
<p>当然它会按如下内容打印</p>
<div class="highlight-python"><pre>-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch</pre>
</div>
<p>Note that the <tt class="xref docutils literal"><span class="pre">sort()</span></tt> method of the list of keyword argument names is
called before printing the contents of the <tt class="docutils literal"><span class="pre">keywords</span></tt> dictionary; if this is
not done, the order in which the arguments are printed is undefined.</p>
<p>注意在打印 <tt class="docutils literal"><span class="pre">关系字</span></tt> 参数字典的内容前先调用 <tt class="xref docutils literal"><span class="pre">sort()</span></tt> 方法。否则的话，打印参数时的顺序是未定义的。</p>
</div>
<div class="section" id="arbitrary-argument-lists">
<span id="tut-arbitraryargs"></span><h3>4.7.3. Arbitrary Argument Lists 可变参数列表<a class="headerlink" href="#arbitrary-argument-lists" title="Permalink to this headline">¶</a></h3>
<p id="index-1473">Finally, the least frequently used option is to specify that a function can be
called with an arbitrary number of arguments.  These arguments will be wrapped
up in a tuple (see <a class="reference external" href="datastructures.html#tut-tuples"><em>Tuples and Sequences 元组和序列</em></a>).  Before the variable number of arguments,
zero or more normal arguments may occur. :</p>
<p>最后，一个最不常用的选择是可以让函数调用可变个数的参数。这些参数被包装
进一个元组（参见 <a class="reference external" href="datastructures.html#tut-tuples"><em>Tuples and Sequences 元组和序列</em></a> ）。在这些可变个数的参数之前，可以有零到多个普通的参数</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">write_multiple_items</span><span class="p">(</span><span class="nb">file</span><span class="p">,</span> <span class="n">separator</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">):</span>
    <span class="nb">file</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">separator</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">args</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="section" id="unpacking-argument-lists">
<span id="tut-unpacking-arguments"></span><h3>4.7.4. Unpacking Argument Lists 参数列表的分拆<a class="headerlink" href="#unpacking-argument-lists" title="Permalink to this headline">¶</a></h3>
<p>The reverse situation occurs when the arguments are already in a list or tuple
but need to be unpacked for a function call requiring separate positional
arguments.  For instance, the built-in <a title="range" class="reference external" href="../library/functions.html#range"><tt class="xref docutils literal"><span class="pre">range()</span></tt></a> function expects separate
<em>start</em> and <em>stop</em> arguments.  If they are not available separately, write the
function call with the  <tt class="docutils literal"><span class="pre">*</span></tt>-operator to unpack the arguments out of a list
or tuple:</p>
<p>另有一种相反的情况: 当你要传递的参数已经是一个列表，但要调用的函数却接受
分开一个个的参数值. 这时候你要把已有的列表拆开来. 例如内建函数 <a title="range" class="reference external" href="../library/functions.html#range"><tt class="xref docutils literal"><span class="pre">range()</span></tt></a>
需要要独立的 <em>start</em>, <em>stop</em> 参数. 你可以在调用函数时加一个 <tt class="docutils literal"><span class="pre">*</span></tt> 操作符来自动
把参数列表拆开</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span>             <span class="c"># normal call with separate arguments</span>
<span class="go">[3, 4, 5]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">6</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>            <span class="c"># call with arguments unpacked from a list</span>
<span class="go">[3, 4, 5]</span>
</pre></div>
</div>
<p id="index-1474">In the same fashion, dictionaries can deliver keyword arguments with the <tt class="docutils literal"><span class="pre">**</span></tt>-operator:</p>
<p>以同样的方式，可以使用 <tt class="docutils literal"><span class="pre">**</span></tt> 操作符分拆关键字参数为字典</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">parrot</span><span class="p">(</span><span class="n">voltage</span><span class="p">,</span> <span class="n">state</span><span class="o">=</span><span class="s">&#39;a stiff&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&#39;voom&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="s">&quot;-- This parrot wouldn&#39;t&quot;</span><span class="p">,</span> <span class="n">action</span><span class="p">,</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="s">&quot;if you put&quot;</span><span class="p">,</span> <span class="n">voltage</span><span class="p">,</span> <span class="s">&quot;volts through it.&quot;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="s">&quot;E&#39;s&quot;</span><span class="p">,</span> <span class="n">state</span><span class="p">,</span> <span class="s">&quot;!&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s">&quot;voltage&quot;</span><span class="p">:</span> <span class="s">&quot;four million&quot;</span><span class="p">,</span> <span class="s">&quot;state&quot;</span><span class="p">:</span> <span class="s">&quot;bleedin&#39; demised&quot;</span><span class="p">,</span> <span class="s">&quot;action&quot;</span><span class="p">:</span> <span class="s">&quot;VOOM&quot;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parrot</span><span class="p">(</span><span class="o">**</span><span class="n">d</span><span class="p">)</span>
<span class="go">-- This parrot wouldn&#39;t VOOM if you put four million volts through it. E&#39;s bleedin&#39; demised !</span>
</pre></div>
</div>
</div>
<div class="section" id="lambda-forms-lambda">
<span id="tut-lambda"></span><h3>4.7.5. Lambda Forms Lambda 形式<a class="headerlink" href="#lambda-forms-lambda" title="Permalink to this headline">¶</a></h3>
<p>By popular demand, a few features commonly found in functional programming
languages like Lisp have been added to Python.  With the <a class="reference external" href="../reference/expressions.html#lambda"><tt class="xref docutils literal"><span class="pre">lambda</span></tt></a>
keyword, small anonymous functions can be created. Here&#8217;s a function that
returns the sum of its two arguments: <tt class="docutils literal"><span class="pre">lambda</span> <span class="pre">a,</span> <span class="pre">b:</span> <span class="pre">a+b</span></tt>.  Lambda forms can be
used wherever function objects are required.  They are syntactically restricted
to a single expression.  Semantically, they are just syntactic sugar for a
normal function definition.  Like nested function definitions, lambda forms can
reference variables from the containing scope:</p>
<p>出于实际需要，有几种通常在函数式编程语言例如 Lisp 中出现的功能加入到了
Python 。通过 <a class="reference external" href="../reference/expressions.html#lambda"><tt class="xref docutils literal"><span class="pre">lambda</span></tt></a> 关键字，可以创建短小的匿名函数。这里有一个函数返
回它的两个参数的和： <tt class="docutils literal"><span class="pre">lambda</span> <span class="pre">a,</span> <span class="pre">b:</span> <span class="pre">a+b</span></tt> 。 Lambda 形式可以用于任何需要的
函数对象。出于语法限制，它们只能有一个单独的表达式。语义上讲，它们只是
普通函数定义中的一个语法技巧。类似于嵌套函数定义，lambda 形式可以从外
部作用域引用变量</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">make_incrementor</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span> <span class="o">+</span> <span class="n">n</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">make_incrementor</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">42</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">43</span>
</pre></div>
</div>
</div>
<div class="section" id="documentation-strings">
<span id="tut-docstrings"></span><h3>4.7.6. Documentation Strings 文档字符串<a class="headerlink" href="#documentation-strings" title="Permalink to this headline">¶</a></h3>
<p id="index-1475">There are emerging conventions about the content and formatting of documentation
strings.</p>
<p>这里介绍的文档字符串的概念和格式。</p>
<p>The first line should always be a short, concise summary of the object&#8217;s
purpose.  For brevity, it should not explicitly state the object&#8217;s name or type,
since these are available by other means (except if the name happens to be a
verb describing a function&#8217;s operation).  This line should begin with a capital
letter and end with a period.</p>
<p>第一行应该是关于对象用途的简介。简短起见，不用明确的陈述对象名或类型，
因为它们可以从别的途径了解到（除非这个名字碰巧就是描述这个函数操作的动
词）。这一行应该以大写字母开头，以句号结尾。</p>
<p>If there are more lines in the documentation string, the second line should be
blank, visually separating the summary from the rest of the description.  The
following lines should be one or more paragraphs describing the object&#8217;s calling
conventions, its side effects, etc.</p>
<p>如果文档字符串有多行，第二行应该空出来，与接下来的详细描述明确分隔。接
下来的文档应该有一或多段描述对象的调用约定、边界效应等。</p>
<p>The Python parser does not strip indentation from multi-line string literals in
Python, so tools that process documentation have to strip indentation if
desired.  This is done using the following convention. The first non-blank line
<em>after</em> the first line of the string determines the amount of indentation for
the entire documentation string.  (We can&#8217;t use the first line since it is
generally adjacent to the string&#8217;s opening quotes so its indentation is not
apparent in the string literal.)  Whitespace &#8220;equivalent&#8221; to this indentation is
then stripped from the start of all lines of the string.  Lines that are
indented less should not occur, but if they occur all their leading whitespace
should be stripped.  Equivalence of whitespace should be tested after expansion
of tabs (to 8 spaces, normally).</p>
<p>Python 的解释器不会从多行的文档字符串中去除缩进，所以必要的时候应当自己
清除缩进。这符合通常的习惯。第一行之后的第一个非空行决定了整个文档的缩
进格式。（我们不用第一行是因为它通常紧靠着起始的引号，缩进格式显示的不
清楚。）留白“相当于”是字符串的起始缩进。每一行都不应该有缩进，如果有
缩进的话，所有的留白都应该清除掉。留白的长度应当等于扩展制表符的宽度
（通常是8个空格）。</p>
<p>Here is an example of a multi-line docstring:</p>
<p>以下是一个多行文档字符串的示例</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">my_function</span><span class="p">():</span>
<span class="gp">... </span>    <span class="sd">&quot;&quot;&quot;Do nothing, but document it.</span>
<span class="gp">...</span><span class="sd"></span>
<span class="gp">... </span><span class="sd">    No, really, it doesn&#39;t do anything.</span>
<span class="gp">... </span><span class="sd">    &quot;&quot;&quot;</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">my_function</span><span class="o">.</span><span class="n">__doc__</span>
<span class="go">Do nothing, but document it.</span>

<span class="go">    No, really, it doesn&#39;t do anything.</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="intermezzo-coding-style">
<span id="tut-codingstyle"></span><h2>4.8. Intermezzo: Coding Style 插曲：编码风格<a class="headerlink" href="#intermezzo-coding-style" title="Permalink to this headline">¶</a></h2>
<p id="index-1476">Now that you are about to write longer, more complex pieces of Python, it is a
good time to talk about <em>coding style</em>.  Most languages can be written (or more
concise, <em>formatted</em>) in different styles; some are more readable than others.
Making it easy for others to read your code is always a good idea, and adopting
a nice coding style helps tremendously for that.</p>
<p>此时你已经可以写一此更长更复杂的 Python 程序，是时候讨论一下
<em>编码风格</em> 了。大多数语言可以写（或者更明白的说， <em>格式化</em> ）作几种不
同的风格。有些比其它的更好读。让你的代码对别人更易读是个好想法，养成良
好的编码风格对此很有帮助。</p>
<p>For Python, <span class="target" id="index-1477"></span><a class="reference external" href="http://www.python.org/dev/peps/pep-0008"><strong>PEP 8</strong></a> has emerged as the style guide that most projects adhere to;
it promotes a very readable and eye-pleasing coding style.  Every Python
developer should read it at some point; here are the most important points
extracted for you:</p>
<p>对于 Python， <span class="target" id="index-1478"></span><a class="reference external" href="http://www.python.org/dev/peps/pep-0008"><strong>PEP 8</strong></a> 引入了大多数项目遵循的风格指导。它给出了一个高
度可读，视觉友好的编码风格。每个 Python 开发者都应该读一下，大多数要点
都会对你有帮助：</p>
<ul>
<li><p class="first">Use 4-space indentation, and no tabs.</p>
<p>使用 4 空格缩进，而非 TAB。</p>
<p>4 spaces are a good compromise between small indentation (allows greater
nesting depth) and large indentation (easier to read).  Tabs introduce
confusion, and are best left out.</p>
<p>在小缩进（可以嵌套更深）和大缩进（更易读）之间，4空格是一个很好的折
中。TAB 引发了一些混乱，最好弃用。</p>
</li>
<li><p class="first">Wrap lines so that they don&#8217;t exceed 79 characters.</p>
<p>折行以确保其不会超过 79 个字符。</p>
<p>This helps users with small displays and makes it possible to have several
code files side-by-side on larger displays.</p>
<p>这有助于小显示器用户阅读，也可以让大显示器能并排显示几个代码文件。</p>
</li>
<li><p class="first">Use blank lines to separate functions and classes, and larger blocks of
code inside functions.</p>
<p>使用空行分隔函数和类，以及函数中的大块代码。</p>
</li>
<li><p class="first">When possible, put comments on a line of their own.</p>
<p>可能的话，注释独占一行</p>
</li>
<li><p class="first">Use docstrings.</p>
<p>使用文档字符串</p>
</li>
<li><p class="first">Use spaces around operators and after commas, but not directly inside
bracketing constructs: <tt class="docutils literal"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">f(1,</span> <span class="pre">2)</span> <span class="pre">+</span> <span class="pre">g(3,</span> <span class="pre">4)</span></tt>.</p>
<p>把空格放到操作符两边，以及逗号后面，但是括号里侧不加空格： <tt class="docutils literal"><span class="pre">a</span> <span class="pre">=</span>
<span class="pre">f(1,</span> <span class="pre">2)</span> <span class="pre">+</span> <span class="pre">g(3,</span> <span class="pre">4)</span></tt> 。</p>
</li>
<li><p class="first">Name your classes and functions consistently; the convention is to use
<tt class="docutils literal"><span class="pre">CamelCase</span></tt> for classes and <tt class="docutils literal"><span class="pre">lower_case_with_underscores</span></tt> for functions
and methods.  Always use <tt class="docutils literal"><span class="pre">self</span></tt> as the name for the first method argument
(see <a class="reference external" href="classes.html#tut-firstclasses"><em>A First Look at Classes 初识类</em></a> for more on classes and methods).</p>
<p>统一函数和类命名。推荐类名用 <tt class="docutils literal"><span class="pre">驼峰命名``，</span> <span class="pre">函数和方法名用</span>
<span class="pre">``小写_和_下划线</span></tt> 。 总是用 <tt class="docutils literal"><span class="pre">self</span></tt> 作为方法的第一个参数（关于类和
方法的知识详见 <a class="reference external" href="classes.html#tut-firstclasses"><em>A First Look at Classes 初识类</em></a> ）。</p>
</li>
<li><p class="first">Don&#8217;t use fancy encodings if your code is meant to be used in international
environments.  Plain ASCII works best in any case.</p>
</li>
</ul>
<p>　在国际化环境中不要随意使用自己喜欢的编码，　纯 ASCII 文本总是工作的最好。
（作为东方人，我有不同的见解，个人推荐首选 utf-8——译者）</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id3" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Actually, <em>call by object reference</em> would be a better description,
since if a mutable object is passed, the caller will see any changes the
callee makes to it (items inserted into a list).</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id4" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[2]</a></td><td>实际上， <em>引用对象调用</em> 描述的更为准确。如果传入一个可变对像，调用
者会看到调用操作带来的任何变化（如子项插入到列表中）。</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="../contents.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="#">4. More Control Flow Tools 深入流程控制</a><ul>
<li><a class="reference external" href="#if-statements-if">4.1. <tt class="docutils literal"><span class="pre">if</span></tt> Statements <tt class="docutils literal"><span class="pre">if</span></tt> 語句</a></li>
<li><a class="reference external" href="#for-statements-for">4.2. <tt class="docutils literal"><span class="pre">for</span></tt> Statements <tt class="docutils literal"><span class="pre">for</span></tt> 语句</a></li>
<li><a class="reference external" href="#the-range-function-range">4.3. The <tt class="docutils literal"><span class="pre">range()</span></tt> Function <tt class="docutils literal"><span class="pre">range()</span></tt> 函数</a></li>
<li><a class="reference external" href="#break-and-continue-statements-and-else-clauses-on-loops-break-continue-else">4.4. <tt class="docutils literal"><span class="pre">break</span></tt> and <tt class="docutils literal"><span class="pre">continue</span></tt> Statements, and <tt class="docutils literal"><span class="pre">else</span></tt> Clauses on Loops break 和 continue 语句, 以及 循环中的 else 子句</a></li>
<li><a class="reference external" href="#pass-statements-pass">4.5. <tt class="docutils literal"><span class="pre">pass</span></tt> Statements <tt class="docutils literal"><span class="pre">pass</span></tt> 语句</a></li>
<li><a class="reference external" href="#defining-functions">4.6. Defining Functions 定义函数</a></li>
<li><a class="reference external" href="#more-on-defining-functions">4.7. More on Defining Functions 深入函数定义</a><ul>
<li><a class="reference external" href="#default-argument-values">4.7.1. Default Argument Values 参数默认值</a></li>
<li><a class="reference external" href="#keyword-arguments">4.7.2. Keyword Arguments 关键字参数</a></li>
<li><a class="reference external" href="#arbitrary-argument-lists">4.7.3. Arbitrary Argument Lists 可变参数列表</a></li>
<li><a class="reference external" href="#unpacking-argument-lists">4.7.4. Unpacking Argument Lists 参数列表的分拆</a></li>
<li><a class="reference external" href="#lambda-forms-lambda">4.7.5. Lambda Forms Lambda 形式</a></li>
<li><a class="reference external" href="#documentation-strings">4.7.6. Documentation Strings 文档字符串</a></li>
</ul>
</li>
<li><a class="reference external" href="#intermezzo-coding-style">4.8. Intermezzo: Coding Style 插曲：编码风格</a></li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="introduction.html"
                                  title="previous chapter">3. An Informal Introduction to Python Python 概要介绍</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="datastructures.html"
                                  title="next chapter">5. Data Structures 数据结构</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/tutorial/controlflow.txt"
         rel="nofollow">Show Source</a></li>
</ul>

          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="datastructures.html" title="5. Data Structures 数据结构"
             >next</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="3. An Informal Introduction to Python Python 概要介绍"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.7 documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Tutorial</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2010, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.  
    <a href="http://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Oct 04, 2010.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.5.
    </div>

  </body>
</html>